package edu.spsu.library;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import edu.spsu.R;
import edu.spsu.utils.UIUtils;
import edu.spsu.utils.Util;

public class LibraryActivity extends ListActivity {
	private static String TAG = LibraryActivity.class.getName();
	private EditText edittext;
	private Spinner spinner;
	private Feed feed = null;

	public final String RSS_PREFIX = "http://gilfind.spsu.edu/vufind/Search/Results?lookfor=";
	public final String PRE_SUFFIX = "&type=";
	public final String RSS_SUFFIX = "&view=rss";


	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.library_feed);
		edittext = (EditText)findViewById(R.id.feedtitle);
		spinner = (Spinner)findViewById(R.id.feedcriterion);
		
		reportLifeCycle("onCreate");
	}

	/** Called when the activity is finished. */
	@Override
	public void onDestroy() {
		super.onDestroy();

		reportLifeCycle("onDestroy");
	}

	private void report(Object o) {

		Util.report(this, TAG, o, false);
	}

	private void reportLifeCycle(Object o) {

		Util.report(this, TAG, o+" completed successfully", false);
	}

	private void reportException(Object o) {

		Util.report(this, TAG, "Exception Thrown: "+o, true);
	}

	private Feed getFeed(String urlToRssFeed, ProgressDialog pd)
	{
		// instantiate our handler
		final RDFHandler theRdfHandler = new RDFHandler(this);

		try
		{
			// setup the url
			URL url = new URL(urlToRssFeed);

			// create the factory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// create a parser
			SAXParser parser = factory.newSAXParser();

			// create the reader (scanner)
			XMLReader xmlreader = parser.getXMLReader();

			// assign our handler
			xmlreader.setContentHandler(theRdfHandler);
			// get our data via the url class
			InputSource is = new InputSource(url.openStream());

			// perform the synchronous parse           
			xmlreader.parse(is);

			report("Loaded data from online feed.");
			
			UIUtils.hideProgressDialog(pd);
		}
		catch (Exception ee)
		{
			reportException(ee);
			UIUtils.hideProgressDialog(pd);
		}

		// get the results - should be a fully populated RSSFeed instance, or null on error
		return theRdfHandler.getFeed();
	}

	@Override
	protected void onListItemClick(ListView parent, View v, int position, long id)
	{
		Util.report(this,TAG, feed.getItem(position).getTitle(), false);

		Intent itemintent = new Intent(this, ShowDescription.class);
		itemintent.putExtra("link", feed.getItem(position).getLink());

		report("Starting ShowDescription Activity.");
		startActivity(itemintent);
	}

	public void onClick(View v)
	{
		final String text = edittext.getText().toString();
		final int criterion = spinner.getSelectedItemPosition();
		final String choice = (String) spinner.getItemAtPosition(criterion);
		final ProgressDialog pd = UIUtils.showProgressDialog(this, choice+": ( " + text 
				+" )","Loading your reference search results.");

		new Thread(new Runnable(){
			@Override
			public void run() {
				
				String type = null;
				switch(criterion)
				{
					case 1: type = "Title"; break;
					case 2: type = "TitleSubject"; break;
					case 3: type = "JournalTitle"; break;
					case 4: type = "Author"; break;
					case 5: type = "Subject"; break;
					case 6: type = "CallNumber"; break;
					case 7: type = "Sudoc"; break;
					case 8: type = "ISN"; break;
					case 9: type = "oclc_num"; break;
					case 10: type = "tag"; break;
					default: type = "AllFields"; break;
				}
				
				// go get the library feed!
				if(!text.equals("")) feed = LibraryActivity.this.getFeed(
					RSS_PREFIX + text.replace(" ", "+") + PRE_SUFFIX + type +RSS_SUFFIX, pd);
				updateDisplay();

				report("Updated search results.");
			}
		}).start();
	}

	private void updateDisplay()
	{   
		runOnUiThread(new Runnable() {

			@Override
			public void run() {

				if (feed == null)
				{
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						LibraryActivity.this,android.R.layout.simple_list_item_1,
						new String[]{"No References Available"});

					setListAdapter(adapter);

					return;
				}

				ArrayAdapter<RDFItem> adapter = new ArrayAdapter<RDFItem>(
						LibraryActivity.this,android.R.layout.simple_list_item_1,
						feed.getAllItems());

				setListAdapter(adapter);

				setSelection(0);

			}
		});
	}
	
	public void taskBarClick(View v) {
		if(v.getId() != R.id.goToLibraryButton)
			Util.taskBarClick(v);
	}
}